package com.sunxueqi.framework.security.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sunxueqi.common.utils.ServletUtils;
import com.sunxueqi.framework.security.LoginUser;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;

@Service("permissionService")
public class PermissionService {

	@Autowired
	private TokenService tokenService;
	
	/**
	 * 验证用户是否具备某权限
	 * @param permission 要检测的权限字符串
	 * @return 用户是否具备该权限，若具备，则返回true
	 */
	public boolean hasPermission(String permission) {
		LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
		if (ObjectUtil.isNull(loginUser) || ObjectUtil.isEmpty(loginUser.getPermissions())) {
			return false;
		}
		return hasPermissions(loginUser.getPermissions(), permission);
	}
	
	/**
	 * 验证用户是否不具备某权限
	 * @param permission 要检测的权限字符串
	 * @return 用户是否具备该权限，若不具备，则返回true
	 */
	public boolean lackPermission(String permission) {
		return !hasPermission(permission);
	}
	
	/**
	 * 判断某权限列表是否包含某一权限
	 * @param permissions 权限列表
	 * @param permission 要检测的权限
	 * @return	若包含则返回true
	 */
	private boolean hasPermissions(List<String> permissions, String permission) {
		return permissions.contains(permission) || permissions.contains(StrUtil.trim(permission));
	}
	
	
}
